package com.lihaozhe.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lihaozhe.dto.Role;
import com.lihaozhe.dto.SecUser;
import com.lihaozhe.mapper.RoleMapper;
import com.lihaozhe.mapper.SecUserMapper;
import com.lihaozhe.util.result.ResultCode;
import com.lihaozhe.util.string.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 李昊哲
 * @version 1.0
 * 2021/12/10 下午1:55
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class UserService implements UserDetailsService {
    private final PasswordEncoder passwordEncoder;
    private final SecUserMapper secUserMapper;
    private final RoleMapper roleMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("获取的账号 >>> {}", username);
        // 1、擦好像数据库中判断账号是否存在如果不存在则抛出UsernameNotFoundException异常
        if (StringUtil.isBlank(username)) {
            throw new UsernameNotFoundException(ResultCode.ACCOUNT_ISNULL.getMsg());
        }
        // 2、根据账号查询到的密码（注册是已经加密过）进行解析，或者直接把账号密码放入构造方法
        QueryWrapper<SecUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        SecUser secUser = secUserMapper.selectOne(wrapper);
        if (secUser == null) {
            throw new UsernameNotFoundException(ResultCode.ACCOUNT_NOT_EXISTS.getMsg());
        }
        System.out.println(secUser.getUid());
        List<Role> roles = roleMapper.selectRolsByUid(secUser.getUid());
        String password = passwordEncoder.encode(secUser.getPassword());
        if (roles == null) {
            return new User(username, password, AuthorityUtils.createAuthorityList());
        }
        roles.forEach(role -> log.info("角色名称 >>> {}",role.getRoleName()));
        List<GrantedAuthority> roleNames = roles.stream().map(role -> new SimpleGrantedAuthority(role.getRoleName())).collect(Collectors.toList());
        return new User(username, password, roleNames);
    }
}